package com.maozw.api.gateway.route;

import com.maozw.api.gateway.pojo.ZuulRouteVO;
import com.maozw.api.gateway.util.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MAOZW
 * @Description: ${todo}
 * @date 2018/8/22 14:09
 */

public class LoadRouteFromDB implements LoadRoute {

    JdbcTemplate jdbcTemplate;

    public Map<String, ZuulProperties.ZuulRoute> loadRoute(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        return loadRoute();
    }

    @Override
    public Map<String, ZuulProperties.ZuulRoute> loadRoute() {
        Map<String, ZuulProperties.ZuulRoute> routes = new LinkedHashMap<>();
        List<ZuulRouteVO> results = jdbcTemplate.query("select * from gateway_api_define where enabled = true ",new BeanPropertyRowMapper<>(ZuulRouteVO.class));
        for (ZuulRouteVO result : results) {
            if(StringUtils.isEmpty(result.getPath()) || StringUtils.isEmpty(result.getUrl()) ){
                continue;
            }
            ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
            try {
                org.springframework.beans.BeanUtils.copyProperties(result,zuulRoute);
            } catch (Exception e) {
                LOGGER.error("=============load zuul route info from db with error==============",e);
            }
            routes.put(zuulRoute.getPath(),zuulRoute);
        }
        return routes;
    }
}
